﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Debug = UnityEngine.Debug;
using System.IO;
using Framework;
using UnityEditor;
using Sirenix.Utilities;

namespace FrameworkEditor
{
    public static class BuildLangConfig
    {
        private static readonly string LangRootDir = "Assets/ZResourcesLib/lang";
        private static readonly string LangCfgPath = "configs/langcfg";
        public static void RefreshLangCfg()
        {
            string json = JsonHelper.Serialize(GetLangCfg());
            Debug.Log("BuildLangConfig.RefreshLangCfg json:\n" + json);
            var jsonPath = Application.dataPath + "/" + FrameworkSettings.ResourcesLibName + "/" + LangCfgPath + ".json";
            FileHelper.WriteTextToPath(jsonPath, json);
            GetUnsupportedLangResRealPath();
            AssetDatabase.Refresh();
        }
        public static void Build(string platformName)
        {
            string json = JsonHelper.Serialize(GetLangCfg());
            Debug.Log("BuildLangConfig.Build platformName = " + platformName + "\njson:\n" + json);
            var jsonData = StringHelper.Str2ByteArray(json);
            var data = EditorUtils.RsaEncrypt(jsonData);
            string buildRootPath = Application.dataPath.Replace("Assets", FrameworkSettings.OutResLibName + "/" + platformName);
            FileHelper.WriteAllBytesToPath(buildRootPath + "/" + LangCfgPath + FrameworkSettings.DataExt, data);
        }

        /// <summary>
        /// 获取不被支持的语言的资源路径集合
        /// </summary>
        /// <returns></returns>
        public static HashSet<string> GetUnsupportedLangResRealPath()
        {
            var cfgTab = GetLangCfg();
            var supportedLangs = new string[] { "zh" };
            HashSet<string> supportedSet = new HashSet<string>(supportedLangs);
            HashSet<string> ret = new HashSet<string>();
            foreach (var cfg in cfgTab)
            {
                foreach (var shortcut in cfg.Value)
                {
                    if (supportedSet.Contains(shortcut))
                    {
                        continue;
                    }
                    var path = "lang/" + shortcut + "/" + cfg.Key;
                    ret.Add(path);
                    Debug.Log("GetUnsupportedLangResRealPath path = " + path);
                }
            }
            return ret;
        }

        private static Dictionary<string, string[]> GetLangCfg()
        {
            if (!Directory.Exists(LangRootDir))
            {
                Debug.LogError("BuildLangConfig.Build LangRootDir = " + LangRootDir + " not exists!");
                return null;
            }
            Dictionary<string, HashSet<string>> allCfg = new Dictionary<string, HashSet<string>>();
            HashSet<string> langResPathSet = new HashSet<string>();

            foreach (var item in LanguageHelper.GetAllLangShortcut())
            {
                allCfg[item] = BuildOneLang(item);
                langResPathSet.AddRange(allCfg[item]);
            }

            Dictionary<string, string[]> cfgTab = new Dictionary<string, string[]>();
            foreach (var resPath in langResPathSet)
            {
                cfgTab.Add(resPath, GetOneResLang(allCfg, resPath));
            }
            return cfgTab;
        }

        private static string[] GetOneResLang(Dictionary<string, HashSet<string>> allCfg, string resPath)
        {
            List<string> langSet = new List<string>();
            foreach (var kvp in allCfg)
            {
                if (kvp.Value.Contains(resPath))
                {
                    langSet.Add(kvp.Key);
                }
            }
            return langSet.ToArray();
        }

        private static HashSet<string> BuildOneLang(string langeShortcut)
        {
            HashSet<string> resPathSet = new HashSet<string>();
            string curLangRootDir = LangRootDir + "/" + langeShortcut;
            if (FileHelper.IsDirExists(curLangRootDir))
            {
                foreach (string file in Directory.GetFiles(curLangRootDir, "*.*", SearchOption.AllDirectories))
                {
                    string filePath = FileHelper.GetUnityPath(file);
                    if (filePath.EndsWith(".meta") || filePath.EndsWith("readme.txt"))
                    {
                        continue;
                    }
                    string relativePath = EditorUtils.GetRelativePathToDir(filePath, FrameworkSettings.AssetRootDir + "/lang/" + langeShortcut);
                    Debug.Log("filePath = " + filePath + "\nrelativePath = " + relativePath);
                    resPathSet.Add(relativePath);
                }
            }
            return resPathSet;
        }
    }
}
